package cn.com.miaoto.common;

import cn.com.miaoto.model.LoginUser;
import cn.com.miaoto.mysql.LoginUserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

@Component
public class SessionUserService implements UserDetailsService {

    @Resource
    private LoginUserMapper loginUserMapper;

    @Override
    public UserDetails loadUserByUsername(String loginCode) {
        Condition condition = new Condition(LoginUser.class);
        condition.createCriteria().andEqualTo("userId", loginCode);
        List<LoginUser> loginUserList = loginUserMapper.selectByCondition(condition);
        if (loginUserList !=null && loginUserList.size() >0) {
            return new SessionUserDetails(loginUserList.get(0));
        } else {
            throw new UsernameNotFoundException("user: " + loginCode + " do not exist!");
        }
    }
}
